Ext.BLANK_IMAGE_URL = 'resources/s.gif'; 
var Data;
//存储获取的数据
var DataStore;
//数据存储器
var Pager;
//分页器
var PerCount=10;
//每页的数据量
var Grid;
//GridPanel容器
var selectDataCompanyName;
var selectRowZhaoPinId;
 var t;
 var gridForm;
  var totalCount=1;
var pageCursor=0;
 
function OnGetDataSuccess(jsonText,row,zhaoPinTotalCount)//数据获取成功
{
	try{
   		Data=Ext.util.JSON.decode(jsonText);
   		canclemsg();
	}catch(e){
		canclemsg();
//		alert(e.name+":"+e.message);
	}
	totalCount=zhaoPinTotalCount;
  //将获取的Json数据格式化
   DataStore.loadData(GetPagerData(Data),false);
   DataStore.load();
  //这个很重要
   Pager.doLoad(0);
  //这个很重要
  taskIndex_ZhaoPin=row;
  
}

function GetPagerData(InData)//从静态数据中获取每页的数据
{
   var TempData=//为什么要用'd'作为json数据的根，因为从WebService获取Json数据经查看就是以'd'为根的
  {
    'd':[]
  };
   if(InData.d.length>PerCount)
  {
     for(var i=0;i<=PerCount-1;i++)
    {
       TempData.d.push(InData.d);
    }
  }
   else
  {
     for(var i=0;i<=InData.d.length-1;i++)
    {
       TempData.d.push(InData.d);
    }
  }
   return TempData;
}
function SerGrid()
{
	//获取数据之前的Loading数据
   Data=
  {
    'd':[
    {
      'id':'数据载入中',
      'companyName':'数据载入中',
      'contactName':'数据载入中',
      'jobexperience':'数据载入中',
      'contactPosition':'数据载入中',
      'telNumber':'数据载入中',
      'mobileNumber':'数据载入中',
      'faxNumber':'数据载入中',
      'address':'数据载入中',
      'postCode':'数据载入中',
      'webSite1':'数据载入中',
      'webSite2':'数据载入中',
      'minDegree':'数据载入中',
      'manageExperience':'数据载入中',
      'businessMode':'数据载入中',
      'registeredCapital':'数据载入中',
      'establishedDate':'数据载入中',
      'establishedAddress':'数据载入中',
      'businessType':'数据载入中',
      'representative':'数据载入中',
      'employeesNum':'数据载入中',
      'annualTurnover':'数据载入中',
      'brandName':'数据载入中',
      'customerGroups':'数据载入中',
      'infoBody':'数据载入中',
      'lastUpdateTime':'数据载入中',
      'infoSource':'数据载入中',
      'status':'数据载入中',
      'positionDetail':'数据载入中',
      'jobMode':'数据载入中',
      'positionSalary':'数据载入中',
      'positionCategory':'数据载入中',
      'workLocation':'数据载入中',
      'languageRequirements':'数据载入中',
      'recruitmentNumber':'数据载入中',
      'requirementsSex':'数据载入中'
    }
    ]
  };
   DataStore=new Ext.data.Store(
  {
    //数据存储器
     proxy:new Ext.data.MemoryProxy(GetPagerData(Data)),
     reader:new Ext.data.JsonReader(
    {
       root:'d'
    },
    [
    {
       name:'id'
    },
    {
       name:'companyName'
    },
    {
       name:'contactName'
    },
    {
       name:'jobexperience'
    },
    {
       name:'contactPosition'
    },
    {
       name:'telNumber'
    },
    {
       name:'mobileNumber'
    },
    {
       name:'faxNumber'
    },
    {
       name:'emails'
    },
    {
       name:'address'
    },
    {
       name:'postCode'
    },
    {
       name:'webSite1'
    },
    {
       name:'webSite2'
    },
    {
       name:'minDegree'
    },
    {
       name:'manageExperience'
    },
    {
       name:'businessMode'
    },
    {
       name:'registeredCapital'
    },
    {
       name:'establishedDate'
    },
    {
       name:'establishedAddress'
    },
    {
       name:'businessType'
    },
    {
       name:'representative'
    },
    {
       name:'employeesNum'
    },
    {
       name:'annualTurnover'
    },
    {
       name:'brandName'
    },
    {
       name:'customerGroups'
    },
    {
       name:'infoBody'
    },
    {
       name:'lastUpdateTime'
    },
    {
       name:'infoSource'
    },
        {
       name:'status'
    },
	{
       name:'positionDetail'
    },
    {
       name:'jobMode'
    },
    {
       name:'positionSalary'
    },
    {
       name:'positionCategory'
    },
    {
       name:'workLocation'
    },
    {
       name:'languageRequirements'
    },
    {
       name:'recruitmentNumber'
    },
    {
       name:'requirementsSex'
    }
    
    ])
  });
   var ColM=new Ext.grid.ColumnModel(//行定义器
  [
  {
     header:"联系状态",dataIndex:"status",sortable :false,editor: new Ext.form.ComboBox({  
                editable: true,  
                displayField: "status",  
                mode: "local",  
                store: new Ext.data.SimpleStore({  
                    fields: ["status"],  
                    data: [["未联系"],["已联系"],["无意向"],["有意向"],["需跟进"],["已签单"], ["已合作"]]  
                })  ,
               triggerAction: 'all',
               selectOnFocus:true,
                 listeners: {  //为Combo添加select事件   
        select: function(combo, record, index) {   // 该事件会返回选中的项对应在 store中的 record值. index参数是排列号.   
 	   	  		sendNSCommand('CHANGESTATUS'+";"+selectDataCompanyName+";"+record.data.status);
				Data.d[Pager.cursor+selectRowZhaoPinId]['status']=record.data.status;
 	   	    }   
		        }  
            })
  },
  {
     header:"公司名称",dataIndex:"companyName",sortable :true
  },
  {
     header:"联系人",dataIndex:"contactName",sortable :true
  },
  {
     header:"工作经验",dataIndex:"jobexperience",sortable :true
  },
  {
     header:"联系人职位",dataIndex:"contactPosition",sortable :true
  },
  {
     header:"电话号码",dataIndex:"telNumber",sortable :true
  },
  {
     header:"手机号码",dataIndex:"mobileNumber",sortable :true
  },
  {
     header:"传真号码",dataIndex:"faxNumber",sortable :true
  },
  {
     header:"地址",dataIndex:"address",sortable :true
  },
  {
     header:"邮编",dataIndex:"postCode",hidden:true,sortable :true
  },
  {
     header:"网站地址",dataIndex:"webSite1",hidden:true,sortable :true
  },
  {
     header:"学历要求",dataIndex:"minDegree",sortable :true
  },
  {
     header:"管理经验",dataIndex:"manageExperience",hidden:true,sortable :true
  },
  {
     header:"商业模式",dataIndex:"businessMode",hidden:true,sortable :true
  },
  {
     header:"注册资金",dataIndex:"registeredCapital",hidden:true,sortable :true
  },
  {
     header:"注册时间",dataIndex:"establishedDate",hidden:true,sortable :true
  },
  {
     header:"注册地址",dataIndex:"establishedAddress",hidden:true,sortable :true
  },
  {
     header:"商业模式",dataIndex:"businessType",hidden:true,sortable :true
  },
  {
     header:"法人代表",dataIndex:"representative",hidden:true,sortable :true
  },
  {
     header:"雇员人数",dataIndex:"employeesNum",hidden:true,sortable :true
  },
  {
     header:"年营业额",dataIndex:"annualTurnover",hidden:true,sortable :true
  },
  {
     header:"品牌名称",dataIndex:"brandName",hidden:true,sortable :true
  },
  {
     header:"职位描述",dataIndex:"positionDetail",hidden:true,sortable :true
  },
  {
     header:"公司简介",dataIndex:"infoBody",hidden:true,sortable :true
  }
  ]);
   Pager=new Ext.PagingToolbar(
  {
     id:'Grid_Pager',
     pageSize:PerCount,
     store:DataStore,
     displayInfo:true,
     paramNames:
    {
       start:'start',limit:'limit',cid:'cid'
    },
     displayInfo:true,
     displayMsg:'显示第 {0} 条到 {1} 条记录，一共 {2} 条',
     emptyMsg:'没有数据',
     updateInfo:function ()//重写UpdateInfo
    {
       if(this.displayEl)
      {
         var count=this.store.getCount();
         var msg=count==0?this.emptyMsg:String.format(this.displayMsg,pageCursor+1,Math.min(pageCursor+this.pageSize-1,totalCount-1)+1,totalCount);
         this.displayEl.update(msg);
      }
    },
     onLoad:function (store,r,o)//重写OnLoad
    {
       if(!this.rendered)
      {
         this.dsLoaded=[store,r,o];
         return ;
      }
       var d=this.getPageData(),ap=d.activePage,ps=d.pages;
       this.afterTextEl.el.innerHTML=String.format(this.afterPageText,d.pages);
       this.field.dom.value=ap;
       this.first.setDisabled(ap==1);
       this.prev.setDisabled(ap==1);
       this.next.setDisabled(ap==ps);
       this.last.setDisabled(ap==ps);
       this.loading.enable();
       this.loading.setVisible(false);
       this.updateInfo();
    },
     doLoad:function (start)//重写doLoad
    {
    	if(start==0){
    		this.cursor=0;
    	}
       var TempData=
      {
        'd':[]
      };
       var i=0;
       var len=this.pageSize;
       for(i=0;i<len;i++)
      {
         if(Data.d[start+i]!=null)
        {
           TempData.d.push(Data.d[start+i]);
        }
      }
       this.store.loadData(TempData,false);
    },
     readPage : function(d){
     	this.cursor=this.pageSize*(this.field.dom.value-1);
     	 t=this.cursor;
       	this.doLoad(t);
       	pageCursor=t;
       	sendNSCommand('TURNPAGE;'+selectTableName+";"+t+";"+(t+this.pageSize));
    },
     getPageData:function ()//重写getPageData
    {
       var A=totalCount;
       return{
			total:A,
			activePage:Math.ceil((pageCursor+this.pageSize)/this.pageSize),
			pages:A<this.pageSize?1:Math.ceil(A/this.pageSize)}},
     onClick:function (which)//重写onClick
    {
       switch(which)
      {
      	
         case "first":
         t=0;
         this.cursor=Math.max(0,t-this.pageSize);
         this.doLoad(0);
         pageCursor=0;
         sendNSCommand('TURNPAGE;'+selectTableName+";"+t+";"+(t+this.pageSize));
         break;
         case "prev":
         t=pageCursor;
         this.cursor=Math.max(0,t-this.pageSize);
         this.doLoad(Math.max(0,t-this.pageSize));
         pageCursor=pageCursor-10;
         sendNSCommand('TURNPAGE;'+selectTableName+";"+(pageCursor)+";"+(pageCursor+this.pageSize));
         break;
         case "next":
         t=this.cursor;
         this.cursor=t+this.pageSize;
         this.doLoad(t+this.pageSize);
         pageCursor+=t+this.pageSize;   
         sendNSCommand('TURNPAGE;'+selectTableName+";"+(pageCursor)+";"+(pageCursor+this.pageSize));
         break;
         case "last":
         var total=totalCount;
         var extra=total%this.pageSize;
         var lastStart=extra?(total-extra):total-this.pageSize;
         this.cursor=extra?(total-extra):total-this.pageSize;
         this.doLoad(lastStart);
         pageCursor=lastStart; 
         sendNSCommand('TURNPAGE;'+selectTableName+";"+(lastStart)+";"+(lastStart+this.pageSize));
         break;
         case "refresh":
         t=this.cursor;
         this.cursor=t;
         this.doLoad(t);
         break;
      }
    }
  });
  
  
  
    gridForm = new Ext.FormPanel({
        id: 'company-form',
        frame: true,
        labelAlign: 'left',
        title: '名录列表',
        bodyStyle:'padding:5px',
        width: 800,
        height: 735,
        layout: 'column',	
        items: [{
            columnWidth: 1,
            layout: 'fit',
            id:'item1',
            items: {
           		id:'panelGrid',
	            xtype: 'editorgrid',
	            store:DataStore,
	            cm:ColM,
	            sm: new Ext.grid.RowSelectionModel({
	                singleSelect: true,
	                listeners: {
	                    rowselect: function(sm, row, rec) {
	                    	selectDataCompanyName = rec.data.companyName;
	                    	selectRowZhaoPinId=row;
	                        Ext.getCmp("company-form").getForm().loadRecord(rec);
	                    }
	                }
	            }),
	            tbar:[{
		            text:'开始搜索',
		            tooltip:'开始搜索',
		            handler:function (){if(typeof(selectTableName)=="undefined"){alert("请在任务列表中选择需要开始搜索的任务");return;}try{msg('正在搜索数据中。。。</p>&nbsp;</p><a class=abutton onclick=stopSearch()>停止搜索</a></p>')}catch(e){}sendNSCommand('STARTSEARCH'); } ,
		            iconCls:'start'
			        }, '-', {
			            text:'停止搜索',
			            tooltip:'停止搜索',
			            handler:function (){if(typeof(selectTableName)=="undefined"){alert("没有开始搜索任务，无法进行此操作");return;}msg("正在停止搜索，请稍后。。。");sendNSCommand('STOPSEARCH');},
			            iconCls:'stop'
			        }, '-', {
			            text:'删除任务',
			            tooltip:'删除任务',
			            handler:function (){
			            	if(typeof(selectTableName)=="undefined"){
			            		alert("请在任务列表中选择需要删除的任务")
			            		return;
			            	}
			            	var answer = confirm("删除任务将会同时删除已完成的搜索列表，请确认是否删除")
							if (answer){
			            		sendNSCommand('DELETETASK');
			            	}else{
			            		return;
			            	}},
			            iconCls:'delete'
			        }	, '-',      {
		            text:'导出数据',
		            tooltip:'导出数据',
		            handler:function (){
		            	if(typeof(selectTableName)!="undefined")
		            	{
		            		msg();
		            		sendNSCommand('derivedExcel'+selectTableName);
		            	}else{
		            		alert("请在任务列表中选择需要导出的数据！");
		            	}
		            } ,
		            buttonAlign:'center',
		            iconCls:'download'
			        }
			        ],
	            height: 310,
	            border: true,
		        listeners: {
		        	render: function(g) {
		        		g.getSelectionModel().selectRow(0);
		        	},
		        	delay: 10 // Allow rows to be rendered.
		        },
		        bbar:Pager
        	}
        },{
        	columnWidth: 1,
            xtype: 'panel',
            autoHeight: true,
            items: [
                        
           {   layout : 'table',
               layoutConfig : {
                 columns : 5 //设置表格布局默认列数为4列
               },
               
           
 	items:[	
	{
     title:'',
     height:2,
     colspan : 5  //设置跨列
    },
    {
     title:'',
     colspan : 1 ,  //设置跨列
	 defaultType: 'textfield', layout : 'form',
	 items: [{fieldLabel: '公司名称',name: 'companyName',readOnly:'true'
            },{  fieldLabel: '联系人',name: 'contactName',readOnly:'true'
            },{fieldLabel: '联系人职位',name: 'contactPosition',readOnly:'true'
            },{fieldLabel: '电话号码',name: 'telNumber',readOnly:'true'
            },{fieldLabel: '手机号码',name: 'mobileNumber',readOnly:'true'
            },{fieldLabel: '传真号码',name: 'faxNumber',readOnly:'true'
            },{fieldLabel: '公司性质',name: 'businessType',readOnly:'true'
            },{fieldLabel: '公司行业',name: 'businessMode',readOnly:'true'
            }]
    },	
	
	{
     title:'',
     colspan : 1 ,  //设置跨列
	 width:15
    },	
    {
     title:'',
     colspan : 1 ,  //设置跨列
	 defaultType: 'textfield', layout : 'form',
	  items: [{fieldLabel: '工作经验',name: 'jobexperience',readOnly:'true'
            },{fieldLabel: '月薪',name: 'positionSalary',readOnly:'true'
            },{fieldLabel: '职位类别',name: 'positionCategory',readOnly:'true'
            },{fieldLabel: '工作地点',name: 'workLocation',readOnly:'true'
            },{fieldLabel: '招聘人数',name: 'recruitmentNumber',readOnly:'true'
            },{fieldLabel: '工作性质',name: 'jobMode',readOnly:'true'
            },{fieldLabel: '性别要求',name: 'requirementsSex',readOnly:'true'
            },{fieldLabel: '网站地址1',name: 'webSite1',readOnly:'true'
            }]
    },	
	{
     title:'',
     colspan : 1 ,  //设置跨列
	 width:15
    },	
    {
     title:'',
     colspan : 1,   //设置跨列
	 defaultType: 'textfield', layout : 'form',
	  items: [{fieldLabel: '地址',name: 'address',readOnly:'true'
            },{fieldLabel: '注册资金',name: 'registeredCapital',readOnly:'true'
            },{fieldLabel: '注册地址',name: 'establishedAddress',readOnly:'true'
            },{fieldLabel: '法人代表',name: 'representative',readOnly:'true'
            },{fieldLabel: '雇员人数',name: 'employeesNum',readOnly:'true'
            },{fieldLabel: '年营业额',name: 'annualTurnover',readOnly:'true'
            },{fieldLabel: '品牌名称',name: 'brandName',readOnly:'true'
            },{fieldLabel: '邮编',name: 'postCode',readOnly:'true'
            }]
    }
         ,
    {
     title:'',
     colspan : 5   //设置跨列
	 , 
	 defaultType: 'textfield', layout : 'form',
	  items: [
			 {fieldLabel: '职位描述',xtype: 'textarea',name: 'positionDetail',anchor: '100% -53',height:'200',readOnly:'true'
            } ]
    },	
    {
     title:'',
     colspan : 5   //设置跨列
	 , 
	 defaultType: 'textfield', layout : 'form',
	  items: [
			 {fieldLabel: '公司简介',xtype: 'textarea',name: 'infoBody',anchor: '100% -53',height:'200',readOnly:'true'
            } ]
    }
    
    
    ]

					}
				]
        }]
    });



//   DataStore.loadData(GetPagerData(Data),false);
   DataStore.load();
//   Pager.doLoad(0);
  //这个很重要，用来显示Loading数据
}

function addData(jsonStr){
	var newData=Ext.util.JSON.decode(jsonStr);
	totalCount++;
	if(Data.d.length>10){
		Data.d.splice(1,10);
	}
	Data.d.push(newData.d[0]);
	DataStore.loadData(GetPagerData(Data),false);
    DataStore.load();
  //这个很重要 doload最后一页
    var thecurson=(Math.floor((Data.d.length-1)/10))*10;
    Pager.doLoad(thecurson);
    pageCursor=(Math.floor((totalCount-1)/10))*10;
    Pager.cursor = thecurson;
   }


function Main()
{
	SerGrid();
   gridForm.render(document.getElementById("right"));
 //   GetDataFromWebService();
 
}







Ext.onReady(function(){
	Main();
	MenuGrid();
	msg('正在加载搜索数据，请稍后。。。');
//	var Request = new Object();
//	Request = GetRequest();
	sendNSCommand('GETTASK');
});





function GetRequest() {

   var url = location.search; //获取url中"?"符后的字串

   var theRequest = new Object();

   if (url.indexOf("?") != -1) {

      var str = url.substr(1);

      strs = str.split("&");

      for(var i = 0; i < strs.length; i ++) {

         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);

      }

   }

   return theRequest;

}


//------------------------------------------------------------------------------------
 var menuStore;
 var selectTableName=0;
 var menuData ={
    'd':[]
  };
  
  var taskIndex_ZhaoPin=0;
function MenuGrid()
{
   menuStore=new Ext.data.Store(
  {
    //数据存储器
     proxy:new Ext.data.MemoryProxy(menuData),
     reader:new Ext.data.JsonReader(
    {
       root:'d'
    },
    [
       {name: 'id'},
       {name: 'taskName'},
       {name: 'updateTime'},
       {name: 'finishedNum'},
       {name: 'totalNum'},
       {name: 'tableName'}

    ])
  });	



    var grid = new Ext.grid.GridPanel({
        store: menuStore,
        columns: [
            {
                header     : '搜索词',
                flex     : 1,
                width    : 145,
                sortable : false,
                dataIndex: 'taskName'
            },
            {
                header     : '完成数',
                width    : 75,
                sortable : false,
                dataIndex: 'finishedNum'
            },
            {
                header     : '预测总数',
                width    : 75,
                sortable : false,
                dataIndex: 'totalNum'
            }

        ],
        sm: new Ext.grid.RowSelectionModel({
	                singleSelect: true,
	                listeners: {
	                    rowselect: function(sm, row, rec) {
	                    	selectTableName=row;
	                    	pageCursor=0;
	                    	msg("正在加载搜索数据，请稍后。。。");
	                        sendNSCommand('GETSEARCHRESULT'+row);
	                    }
	                }
	            }),
        stripeRows: true,
        height:350,
        width:300,
        title:'任务列表'
    });
    
     

    grid.render(document.getElementById("jqbody-menu"));
}


function OnGetTaskSuccess(jsonText){
	menuData=Ext.util.JSON.decode(jsonText);
	menuStore.loadData(menuData,false);
	canclemsg();
}

function stoploading(){
	if(typeof(selectTableName)=="undefined"){
		selectTableName=0;
	}
	sendNSCommand('GETSEARCHRESULT'+selectTableName);	
	t=0;
	pageCursor=t;
//    Pager.cursor = t;
//    Pager.doLoad(t);
	
}

function updateNum(totalResultNum,startIndex){
	menuData.d[taskIndex_ZhaoPin].finishedNum=startIndex;
	menuData.d[taskIndex_ZhaoPin].totalNum=totalResultNum;
	menuStore.loadData(menuData,false);
}

